<template>
  <div class="monitor-container">
    <div v-for="(param, index) in parameters" :key="index">
      {{ param.name }}：{{ param.value.toFixed(2) }}±{{ param.variation.toFixed(2) }}
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      parameters: [
        { name: 'PH', value: 7.86, variation: 0.35 },
        { name: '温度', value: 25, variation: 0.35 },
        { name: '溶解氧', value: 8.5, variation: 0.35 },
        { name: '氨氮', value: 0.25, variation: 0.35 },
        { name: '总磷', value: 0.25, variation: 0.35 },
        { name: '总氮', value: 1.3, variation: 0.35 }
      ],
      intervalId: null // 用于存储定时器ID
    };
  },
  methods: {
    updateValues() {
      this.parameters.forEach(param => {
        const variation = (Math.random() - 0.5) * param.variation * 2;
        param.value = Math.max(0, param.value + variation); // 确保值不小于0
      });
    },
    startRandomChanges(interval) {
      if (this.intervalId) {
        clearInterval(this.intervalId); // 清除已有的定时器
      }
      this.intervalId = setInterval(() => {
        this.updateValues();
      }, interval);
    },
    stopRandomChanges() {
      if (this.intervalId) {
        clearInterval(this.intervalId); // 清除定时器
        this.intervalId = null;
      }
    }
  },
  mounted() {
    // 启动随机变化，每2000毫秒（2秒）更新一次
    this.startRandomChanges(200);
  },
  beforeUnmount() {
    // 组件销毁前停止随机变化
    this.stopRandomChanges();
  }
}
</script>

<style scoped>
.monitor-container {
  padding: 20px;
  background-color: #f0f0f0;
  border-radius: 8px;
}
.monitor-container div {
  margin-bottom: 10px;
  font-size: 16px;
}
</style>